/*
 * @Author: silence
 * @Date: 2022-02-10 10:52:38
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-07-07 14:37:42
 * @Description: 处理请求返回的数据
 * @FilePath: /flutter_template_app/lib/utils/api/R.dart
 */

import 'package:dio/dio.dart';

class R<T> {
  /**状态码 */
  int? code;

  /**消息 */
  String? msg;

  /** 返回处理过的数据 */
  T? data;

  /** 返回没有处理过的data  */
  dynamic originalData;

  /** count*/
  int? count;

  /**服务器时间戳 */
  String? timestamp;

  /**错误异常 */
  dynamic error;

  /**
   * @description: 处理请求的数据
   * @param {*}
   * @return {*}
   */
  static R fromData(Map<String, dynamic>? data,
      {Function(dynamic map)? handlerData}) {
    R result = R();

    if (data == null || data.isEmpty) {
      result.msg = "数据为空";
      return result;
    }

    // 记录异常
    if (data.containsKey('error')) {
      result.error = data['error'];
      DioError dioError= data['error'];
      if(dioError.type==DioErrorType.cancel){
        // throw MyFutureBuilderException('手动取消', result.error);
      }else{
        // throw MyFutureBuilderException('网络不给力，请稍后重试', result.error);
      }

    }

    if (data.containsKey('code')) {
      result.code = data['code'];
    }

    if (data.containsKey('timestamp')) {
      result.timestamp = "${data['timestamp']}";
    }

    if (data.containsKey('msg')) {
      result.msg = data['msg'];
    }

    if (data.containsKey('data')) {
      // 原始数据
      result.originalData = data['data'];

      // 数据处理一下，考虑数据异常的情况
      if (handlerData != null) {
        try {
          if(data['data']!=null)
          result.data = handlerData(data['data']);
        } catch (e, i) {
         // Mylog.e({'error': e, 'info': i});
        }
      } else {
        result.data = data['data']??null;
      }
    }

    // count
    if (data.containsKey('count')) {
      result.count = data['count'];
    }

    return result;
  }
}
